package com.dongge.service;

import com.dongge.dao.RoleDao;
import com.dongge.entity.Role;
import com.dongge.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Created by zhudong on 2016/8/15.
 */
@Transactional
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserService userService;

    public Set<String> getRoleNamesByUserId(long id) {
        List<Role> roles = roleDao.getRolesByUserId(id);
        Set<String> names = new HashSet<String>();
        for(Role role:roles){
            names.add(role.getName());
        }
        return names;
    }

    public Set<String> getRoleNamesByUsername(String username) {
        User user = userService.getUserByUsername(username);
        if(user==null){
            return new HashSet<String>();
        }
        return getRoleNamesByUserId(user.getId());
    }

    public List<Role> getRolesByUserId(long id) {
        return roleDao.getRolesByUserId(id);
    }

    public List<Role> getRolesByUsername(String username) {
        User user = userService.getUserByUsername(username);
        if(user==null){
            return new LinkedList<Role>();
        }
        return getRolesByUserId(user.getId());
    }

    public List<Role> getRoles() {
        return roleDao.getRoles();
    }

    public long save(Role role) {
        return roleDao.save(role);
    }

    public int update(Role role) {
        return roleDao.update(role);
    }

    public void addUser(long roleId, long userId) {
        User user = userService.getUserById(userId);
        Role role = get(roleId);
        roleDao.addUser(role,user);
    }

    public Role get(long id) {
        return roleDao.get(id);
    }

    /**
     * 如果查询一部对象怎么办（分页问题）
     * select u from User u ,in u.roles r where r.id=:id
     * @param id
     * @return
     */
    public Set<User> getUsersByRoleId(long id) {
        Role role = get(id);
        return role.getUsers();
    }
}
